package com.songshuai.webapi.jobapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.songshuai.webapi.jobapi.common.enumerations.JobType;
import com.songshuai.webapi.jobapi.common.enumerations.ScheduleHisEventType;
import com.songshuai.webapi.jobapi.common.settings.CacheKeys;
import com.songshuai.webapi.jobapi.dao.edu.StudentScheduleHisMapper;
import com.songshuai.webapi.jobapi.dto.base.QueryResponse;
import com.songshuai.webapi.jobapi.dto.edu.CourseScheduleDto;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentInfo;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentInfoWithBLOBs;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentScheduleHis;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentShitingInfo;
import com.songshuai.webapi.jobapi.service.JobNetPostService;
import com.songshuai.webapi.jobapi.service.ScheduleBaseService;
import com.songshuai.webapi.jobapi.service.SyncLogService;
import com.songshuai.webapi.jobapi.service.SyncScheduleHisService;
import com.songshuai.webapi.jobapi.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Administrator
 * @Date: 2018/11/2 0002 15:53
 * @Description:
 */
@Component
@Slf4j
public class SyncScheduleHisServiceImpl  implements SyncScheduleHisService {

    @Autowired
    StudentScheduleHisMapper scheduleHisMapper;

    @Autowired
    JobNetPostService postService;

    @Autowired
    ScheduleBaseService scheduleBaseService;

    @Autowired
    SyncLogService syncLogService;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void SyncScheduleHis(String begin, String endTime,Integer size) {
        Integer pageIndex=1;
        List<TpoStudentScheduleHis> studentSchedules=new ArrayList<>();
        studentSchedules = scheduleHisMapper.getScheduleHisByUpdateTime(begin,endTime, ScheduleHisEventType.DeleteEvent.getCode(),size,(pageIndex - 1) * size);

        if(studentSchedules==null||studentSchedules.size()==0){
            return;
        }
        log.info("SyncScheduleHis Start");
        while (studentSchedules!=null&&studentSchedules.size()>0){
            List<CourseScheduleDto>courseScheduleDtos=new ArrayList<>();
            //学生的Guid
            List<String>stuGuids=studentSchedules.stream().map(TpoStudentScheduleHis::getStudentGuid).filter(f->f!=null&&f.length()>0).distinct().collect(Collectors.toList());
            List<Integer>lessionIds=studentSchedules.stream().map(TpoStudentScheduleHis::getLessonId).filter(f->f!=null&&f>0).distinct().collect(Collectors.toList());
            Map<Integer, TpoStudentShitingInfo> studentShitingInfoMap =scheduleBaseService.ShiTingInfoByLessonIdMap(lessionIds);
            Map<String, TpoStudentInfoWithBLOBs>studentInfoMap= scheduleBaseService.getStudentInfoMap(stuGuids);
            for(TpoStudentScheduleHis schedule:studentSchedules){
                if(schedule.getLessonId()==null){
                    continue;
                }
                CourseScheduleDto scheduleDto=new CourseScheduleDto();
                scheduleDto.setStatus("1");
                scheduleDto.setLesson_id(String.valueOf(schedule.getLessonId()));
                scheduleDto.setTeacher_name("");
                scheduleDto.setTeacher_id("0");
                scheduleDto.setCourse_id("0");
                scheduleDto.setCrm_teacher_name("");
                scheduleDto.setUser_id("0");
                scheduleDto.setCrm_user_id("0");
                scheduleDto.setUser_id("0");
                scheduleDto.setCrm_course_id("0");
                scheduleDto.setUnit("0");
                scheduleDto.setGw_course_id("0");
                scheduleDto.setCrm_teacher_id("0");
                scheduleDto.setStart_time("");
                scheduleDto.setEnd_time("");
                scheduleDto.setSchedule_total("0");
                scheduleDto.setSchedule_num("0");
                scheduleDto.setAttendance_status("0");
                scheduleDto.setCourse_type("0");
                scheduleDto.setSubject_id("0");
                if(schedule.getStudentGuid()!=null&&schedule.getStudentGuid().length()>0){
                    TpoStudentInfoWithBLOBs studentInfo=studentInfoMap.getOrDefault(schedule.getStudentGuid(),null);
                    if(studentInfo!=null){
                        scheduleDto.setUser_id(studentInfo.getGwId()==null?"0":String.valueOf(studentInfo.getGwId()));
                    }
                }else{
                    TpoStudentShitingInfo shitingInfo=studentShitingInfoMap.getOrDefault(schedule.getLessonId(),null);
                    if(shitingInfo!=null){
                        scheduleDto.setUser_id(shitingInfo.getGw_id()==null?"0":shitingInfo.getGw_id());
                    }
                }
                if(scheduleDto.getUser_id()==null||scheduleDto.getUser_id().length()==0||scheduleDto.getUser_id().equals("0")){
                    continue;
                }
                courseScheduleDtos.add(scheduleDto);
            }
            if(courseScheduleDtos.size()>0){
                String listData= JSON.toJSONString(courseScheduleDtos);
                Map<String,String>parms=new HashMap<>();
                parms.put("list",listData);
                QueryResponse<Map<String,Boolean>> res= postService.PostFormData(parms,"course/courseSchedule");
                if(res!=null){
                    syncLogService.AddLogs(JobType.CourseHisSchedule.getCode(),courseScheduleDtos,res.getData());
                }
                System.out.println(courseScheduleDtos);
                log.info("SyncScheduleHis Start Page_"+pageIndex);
            }
            pageIndex++;
            if(studentSchedules.size()<size){
                break;
            }
            studentSchedules = scheduleHisMapper.getScheduleHisByUpdateTime(begin,endTime, ScheduleHisEventType.DeleteEvent.getCode(),size,(pageIndex - 1) * size);
        }
        log.info("SyncScheduleHis End");
    }

    @Override
    public void SyncCourseScheduleHis(Boolean isFullDay,String beginTime,String endTime) {
        HashOperations<String,String,String> operations=redisTemplate.opsForHash();
        String begin=operations.get(CacheKeys.JOB_TIME_CACHE_KEY, String.valueOf(JobType.CourseHisSchedule.getCode()));
        if(isFullDay||begin==null||begin==""){
            begin= Util.ChangeDateToString(new Date(),"yyyy-MM-dd");
        }
        if(!Util.IsNullAndEmpty(beginTime)){
            begin=beginTime;
        }
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,-10);
        Integer pageSize=50;
        String currentTime=Util.ChangeDateToString(calendar.getTime(),"yyyy-MM-dd HH:mm:ss");
        //删除数据
        SyncScheduleHis(begin,endTime,pageSize);
        if(!isFullDay){
            operations.put(CacheKeys.JOB_TIME_CACHE_KEY,String.valueOf(JobType.CourseHisSchedule.getCode()),currentTime);
        }
    }

    /**
     * 同步历史数据
     * @param lessonIds
     */
    @Override
    public void SyncScheduleHisByIds(List<Integer>lessonIds) {
        List<TpoStudentScheduleHis> studentSchedules=new ArrayList<>();
        studentSchedules = scheduleHisMapper.getScheduleByLessonids(lessonIds);
        if(studentSchedules==null||studentSchedules.size()==0){
            return;
        }

        List<CourseScheduleDto>courseScheduleDtos=new ArrayList<>();
        //学生的Guid
        List<String>stuGuids=studentSchedules.stream().map(TpoStudentScheduleHis::getStudentGuid).filter(f->f!=null&&f.length()>0).distinct().collect(Collectors.toList());
        List<Integer>lessionIds=studentSchedules.stream().map(TpoStudentScheduleHis::getLessonId).filter(f->f!=null&&f>0).distinct().collect(Collectors.toList());
        Map<Integer, TpoStudentShitingInfo> studentShitingInfoMap =scheduleBaseService.ShiTingInfoByLessonIdMap(lessionIds);
        Map<String, TpoStudentInfoWithBLOBs>studentInfoMap= scheduleBaseService.getStudentInfoMap(stuGuids);
        for(TpoStudentScheduleHis schedule:studentSchedules){
            if(schedule.getLessonId()==null){
                continue;
            }
            CourseScheduleDto scheduleDto=new CourseScheduleDto();
            scheduleDto.setStatus("1");
            scheduleDto.setLesson_id(String.valueOf(schedule.getLessonId()));
            scheduleDto.setTeacher_name("");
            scheduleDto.setTeacher_id("0");
            scheduleDto.setCourse_id("0");
            scheduleDto.setCrm_teacher_name("");
            scheduleDto.setUser_id("0");
            scheduleDto.setCrm_user_id("0");
            scheduleDto.setUser_id("0");
            scheduleDto.setCrm_course_id("0");
            scheduleDto.setUnit("0");
            scheduleDto.setGw_course_id("0");
            scheduleDto.setCrm_teacher_id("0");
            scheduleDto.setStart_time("");
            scheduleDto.setEnd_time("");
            scheduleDto.setSchedule_total("0");
            scheduleDto.setSchedule_num("0");
            scheduleDto.setAttendance_status("0");
            scheduleDto.setCourse_type("0");
            scheduleDto.setSubject_id("0");
            if(schedule.getStudentGuid()!=null&&schedule.getStudentGuid().length()>0){
                TpoStudentInfoWithBLOBs studentInfo=studentInfoMap.getOrDefault(schedule.getStudentGuid(),null);
                if(studentInfo!=null){
                    scheduleDto.setUser_id(studentInfo.getGwId()==null?"0":String.valueOf(studentInfo.getGwId()));
                }
            }else{
                TpoStudentShitingInfo shitingInfo=studentShitingInfoMap.getOrDefault(schedule.getLessonId(),null);
                if(shitingInfo!=null){
                    scheduleDto.setUser_id(shitingInfo.getGw_id()==null?"0":shitingInfo.getGw_id());
                }
            }
            if(scheduleDto.getUser_id()==null||scheduleDto.getUser_id().length()==0||scheduleDto.getUser_id().equals("0")){
                continue;
            }
            courseScheduleDtos.add(scheduleDto);
        }
        if(courseScheduleDtos.size()>0){
            String listData= JSON.toJSONString(courseScheduleDtos);
            Map<String,String>parms=new HashMap<>();
            parms.put("list",listData);
            QueryResponse<Map<String,Boolean>> res= postService.PostFormData(parms,"course/courseSchedule");
            if(res!=null){
                syncLogService.AddLogs(JobType.CourseHisSchedule.getCode(),courseScheduleDtos,res.getData());
            }
        }

    }
}
